<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="handleSearchFunc"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFunc">查询</el-button>
      <el-button size="mini" @click="handleAdd"  v-functions="['customer_template_setting_insert']">新增</el-button>
      <el-button size="mini" @click="handleSettingPermissions" v-functions="['customer_template_setting_setUp']">设置</el-button>
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
              ref="table"
              :headers="tableHeaders"
              :data="templateTableData"
              :pagingData="pagingData"
              @pageChange="handleCurrentChange"
              @pageSizeChange="handleSizeChange"
              @checkHeadersChange="checkHeadersChange">
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
                    :show-overflow-tooltip="true"
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop !== 'oprate' && item.prop !== 'status' && item.prop !== 'type'">
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :width="68"
                    :key="index"
                    v-if="item.prop === 'status'">
              <template slot-scope="scope">
                <i class="V7_iconfont V7_iconV7tubiao_dian" :class="scope.row.status === 'enable' ? 'enable-span':'disable-span'"></i><span>{{scope.row.status === 'enable'?'启用':'停用'}}</span>
              </template>
            </u-table-column>
            <u-table-column
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :width="100"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop === 'type'">
              <template slot-scope="scope">
                <span>{{scope.row.type  === 'CUSTOMER' ? '客户模板' : scope.row.type === 'TICKET' ? '工单模板' : '未知模板'}}</span>
              </template>
            </u-table-column>
            <u-table-column
                    :width="120"
                    fixed="right"
                    :label="item.label"
                    :key="index"
                    v-if="item.prop === 'oprate' && item.show">
              <template slot-scope="scope">
                <span @click="handleEdit(scope.row)" class="oprate-span" v-functions="['customer_template_setting_edit']">编辑</span>
                <span @click="handleDeploy(scope.row)" class="oprate-span" v-functions="['customer_template_setting_config']">配置</span>
                <span @click="handleEnableOrDisabled(scope.row)" class="oprate-span" :class="scope.row.status === 'disable'?'':'red-span'" v-functions="['customer_template_setting_enableOrDisable']" v-if="scope.row.type !== 'CUSTOMER'">{{scope.row.status === 'enable' ? '停用': '启用'}}</span>
                <span @click="handleDel(scope.row)" v-functions="['customer_template_setting_delete']" v-if="scope.row.type !== 'CUSTOMER'" class="oprate-span red-span">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <!-- #region 右侧抽屉 新增、编辑 -->
      <cuDrawer
              ref="cuDrawer"
              :type="type"
              :postForm="postForm"
              @handleConfirmAdd="handleConfirmAdd"
              @handleConfirmEdit="handleConfirmEdit"
      ></cuDrawer>
      <!-- #endregion -->
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import cuDrawer from '@/views/config/template/addOrEditTemplate.vue'
import configTable from '@/components/configCommon/table.vue'
import { CommonModule } from '@/store/modules/common'
import { TemplateModule } from '@/store/modules/config/template'
interface DefaultForm {
  applicationId: number
  name: string
  remark: string
  status: string
  type: string
}
interface PageData {
  total: number
  limit: number
  page: number
}
@Component({
  name: 'customerTemplateSetting',
  components: {
    QuickSearch,
    configTable,
    cuDrawer,
    continer
  }
})
export default class CustomerTemplateSetting extends Vue {
  // #region 基础数据
  [x: string]: any
  @Ref() private readonly table!: configTable
  @Ref() private readonly CustomerTemplateSetting!: cuDrawer
  private type: string = 'add' // 新增 || 编辑
  private quickSearchForm: any = {} // 快捷搜索表单 需动态变化
  private listLoading: boolean = false
  private templateTableData = [] // list 数据
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private checkHeaders: [] = [] // 当前展示的表头信息
  private defaultForm: DefaultForm = { // 新增、编辑 初始对象
    applicationId: this.$store.state.common.mpInfo.mpApplicationId,
    name: '',
    remark: '',
    status: 'enable',
    type: 'TICKET'
  }

  private postForm = JSON.parse(JSON.stringify(this.defaultForm))

  private templateStatusData = [ // 模板状态
    { _id: '', name: '全部' },
    { _id: 'enable', name: '启用' },
    { _id: 'disable', name: '停用' }
  ]

  private templateTypeData = [ // 模板类型
    { _id: 'CUSTOMER', name: '客户模板' },
    { _id: 'TICKET', name: '工单模板' }
    // { _id: 'OUTBOUND', name: '外呼任务模板' }
  ]
  // #endregion

  // #region 高级搜索相关
  // 查询
  private handleSearchFunc () {
    this.pagingData.page = 1
    this.initData()
  }
  // #endregion

  // #region 数据表格相关
  // header 表头
  private tableHeaders: object[] = [ // 标头配置信息
    { label: '模板名称', prop: 'name' },
    { label: '备注', prop: 'remark' },
    { label: '状态', prop: 'status', sortable: true },
    { label: '类型', prop: 'type' },
    { label: '最后更新时间', prop: 'updateTime', sortable: true },
    { label: '操作', prop: 'oprate' }
  ]

  private handleEnableOrDisabled (row: any) { // 停用 / 启用
    this.$confirm(`确定要${row.status === 'enable' ? '停用' : '启用'}【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionUrl = row.status === 'enable' ? '/crm/action/template/disable' : '/crm/action/template/enable'
      const data = { url: actionUrl, method: 'GET', data: { id: row._id } }
      TemplateModule.TemplateCommonAction(data).then((res: any) => {
        if (res && res.success) {
          const str = row.status === 'enable' ? `停用【${row.name}成功】` : `启用【${row.name}】成功`
          this.$message({ message: str, type: 'success' })
          this.initData()
        }
      }).catch((e) => {
        console.log(e)
      })
    })
  }

  // operate 编辑某行
  private handleEdit (row: any) {
    (this as any).$refs.cuDrawer.openOrCloseDraw()
    this.postForm = JSON.parse(JSON.stringify(row, [...Object.keys(this.defaultForm), '_id', 'worksheetId']))
    this.type = 'edit'
  }

  // 编辑某行 确认按钮
  private handleConfirmEdit (form) {
    const pF = JSON.parse(JSON.stringify(form))
    TemplateModule.TemplateCommonAction({ url: '/crm/action/template/edit', method: 'POST', data: pF }).then(res => {
      if (res && res.success) {
        (this as any).$refs.cuDrawer.handleCancel()
        this.$message.success('模板编辑成功')
        this.initData()
      }
    }).finally(() => {
      (this as any).$refs.cuDrawer.handleCancel()
    })
  }

  // operate 配置
  private handleDeploy (row: any) {
    this.$router.push({
      // path: '/index/setting_center/template/edit/' +
      //   `templateConfig/${res.data.applicationId}/${res.data.worksheetId}/fields`
      path: `/setting_center/index/customer_template_setting/edit/${row._id}`
    })
  }

  // operate 删除某行
  private handleDel (row: any) {
    this.$confirm('该操作将删除该模板及配置的所有信息，是否确认？', '确认删除模板', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.listLoading = true
      TemplateModule.TemplateCommonAction({ url: `/crm/action/template/del/${row._id}`, method: 'GET', data: {} }).then(res => {
        if (res && res.success) {
          this.$message.success('模板删除成功')
          this.handleSearchFunc()
        }
      }).finally(() => {
        this.listLoading = false
      })
    }).catch(e => {
      console.log(e)
    })
  }

  // 更改表头
  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  // 改变每页行数大小
  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  // 翻页
  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.initData()
  }
  // #endregion

  // #region 页面全局函数
  // 初始化列表
  private initData () {
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    this.listLoading = true
    TemplateModule.TemplateCommonAction({ url: '/crm/action/template/list', method: 'POST', data: actionData }).then(res => {
      if (res && res.success) {
        this.templateTableData = res.list || []
        this.pagingData.total = res.count || 0
      }
    }).finally(() => {
      this.listLoading = false
    })
  }

  // 新增模板
  private handleAdd () {
    this.postForm = JSON.parse(JSON.stringify(this.defaultForm));
    (this as any).$refs.cuDrawer.openOrCloseDraw()
    this.type = 'add'
  }

  // 设置角色权限
  private handleSettingPermissions () {
    this.$router.push({ path: '/setting_center/index/customer_template_setting/settingUserPermissions' })
  }

  // 新增模板 确认按钮
  private handleConfirmAdd (form) {
    const pF = JSON.parse(JSON.stringify(form))
    console.log('handleConfirmAdd form:\n', pF)
    TemplateModule.TemplateCommonAction({ url: '/crm/action/template/save', method: 'POST', data: pF }).then(res => {
      if (res && res.success) {
        (this as any).$refs.cuDrawer.openOrCloseDraw()
        this.$message.success('模板新增成功')
        this.initData()
      }
    })
  }

  private getDictionary (arr) {
    const obj = {}
    arr.map(v => {
      obj[v._id] = { name: v.name, iconClass: v.iconClass }
    })
    return obj
  }

  // #region 生命周期钩子
  private mounted () {
    // 预加载子应用的文件，模板配置
    // prefetchApps([{
    //   name: 'apass-micro-templateConfig',
    //   entry: `${(CommonModule.initConfig as any).platformConfig.mopowerUrl}/templateConfig.html`
    // }])
    this.quickSearchForm = { // 高级搜索数据
      form: {
        name: '',
        status: '',
        type: []
      },
      advSearchOptions: [ // 高级搜索数据
        { label: '模板名称', name: 'name', inputType: 'input', clearable: true, placeholder: '请输入模板名称' },
        { label: '状态', name: 'status', inputType: 'select', clearable: true, selectData: this.templateStatusData, placeholder: '状态' },
        { label: '类型', name: 'type', inputType: 'select', clearable: true, selectData: this.templateTypeData, placeholder: '类型', multiple: true }
      ]
    }
    CommonModule.getMpInfo({ url: '/auth/get/mp/relation', method: 'POST', data: {} }).then(() => {
      this.defaultForm.applicationId = this.$store.state.common.mpInfo.mpApplicationId
    })
    this.handleSearchFunc()
  }

  private beforeRouteLeave (to: any, from: any, next: any) {
    this.$nextTick(() => {
      (this as any).$refs.cuDrawer.handleCancel()
    })
    next()
  }
  // #endregion
}
</script>
<style lang="stylus" scoped>
  .oprate-span,.radio-span
    cursor pointer
    color $c-main
    margin 0 4px
  .red-span,.disable-span
    color $c-danger
  .enable-span
    color $c-green
  .disable-span,.enable-span
    font-size 12px
</style>
